package com.bigdatan.b2c.controller;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



//import org.apache.commons.lang3.WordUtils;
//import org.apache.commons.lang3.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import util.AdvancedUtil;

import com.bigdatan.b2c.conf.WXYMLConfig;
import com.bigdatan.b2c.entity.pojo.SNSUserInfo;
import com.bigdatan.b2c.entity.pojo.WeixinOauth2Token;
import com.bigdatan.b2c.service.user.IUserService;
import com.slsy.weixin.mp.api.WxMpServiceImpl;
import com.slsy.weixin.mp.bean.result.WxMpUser;


/**
 *
 * @Date：2016年12月9日 9:38:31
 * 微信授权 回调
 */
@Controller
@RequestMapping("/wxAuthor")
public class WxAuthor {
	private static Logger log =LoggerFactory.getLogger(WxAuthor.class);
	@Autowired
	private WXYMLConfig wxConfig;
	
	@Resource
	private IUserService userService;
	@Resource
	private WxMpServiceImpl wxMpService;
	
	/**
	 * 用户授权后微信回调地址
	 */
	@RequestMapping("/user")
	public void getUserInfo(HttpServletRequest request,HttpServletResponse response){
		log.info("开始到了微信回调");
		String code = request.getParameter("code");
		String pageAlias = request.getParameter("pageAlias");
		log.info("code:"+code+" pageAlias:"+pageAlias);
		try {
			// 用户同意授权
			if (!"authdeny".equals(code)) {
				// 获取网页授权access_token
				WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getOauth2AccessToken(wxConfig.getAPPID(),
						wxConfig.getSECRET(), code);
				// 网页授权接口访问凭证
				// String accessToken = weixinOauth2Token.getAccessToken();
				// 用户标识
				String openId = weixinOauth2Token.getOpenId();
				// 获取用户信息
				WxMpUser userInfo = wxMpService.userInfo(openId, null);
				log.info("微信用户信息userInfo[{}]", userInfo);
				SNSUserInfo snsUserInfo = new SNSUserInfo();
				// 用户的标识
				snsUserInfo.setOpenId(userInfo.getOpenId());
				// 昵称
				snsUserInfo.setNickname(userInfo.getNickname());
				// 性别（1是男性，2是女性，0是未知）
				snsUserInfo.setSex(userInfo.getSexId());
				// 用户所在国家
				snsUserInfo.setCountry(userInfo.getCountry());
				// 用户所在省份
				snsUserInfo.setProvince(userInfo.getProvince());
				// 用户所在城市
				snsUserInfo.setCity(userInfo.getCity());
				// 用户头像
				snsUserInfo.setHeadImgUrl(userInfo.getHeadImgUrl());
				// SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken2, openId);
				snsUserInfo.setCode(code);

				// 设置要传递的参数
				request.getSession().setAttribute("snsUserInfo", snsUserInfo);
				
				Cookie openIdCookie = new Cookie("com.oauth2.openId",openId);
				openIdCookie.setMaxAge(24*60*60);// 一天 
				response.addCookie(openIdCookie);
				log.info("operID:"+openId);

				response.sendRedirect("http://47.106.156.158:4865/");
			}

		} catch (Exception e) {
			log.error("发生异常："+e.getMessage());
		}
		log.info("微信回调结束");
	}
	
	
	
	
	/**
	 * 用户授权后微信回调地址
	 *//*
	@RequestMapping("/user")
	public void getUserInfo(@RequestParam(required=false,value="code")String code,HttpServletRequest request,HttpServletResponse response,@RequestParam(required=false,value="state")String state){
		log.info("开始到了微信回调");
		JSONObject jsonObject =null;//处理微信返回json数据
		
		User user=null;
		String openid="";//微信用户openid
		String access_token="";//授权码
		String resultStr ="";//接口返回字符
		String requesUrl = Configure.WX_GET_ACCESS_URL;//获取openid地址
		String userinfoUrl= Configure.WX_GET_USER_INFO_URL;//拉取用户信息地址
		try {
			if(!StringUtils.isBlank(code)&&!StringUtils.isBlank(requesUrl)){//开始获取用户openid
				requesUrl = requesUrl.replace("APP_ID",Configure.APP_ID).replace("APP_SECRET",Configure.APP_SECRET).replace("USE_CODE", code);
				resultStr = HttpsUtil.httpsRequest(requesUrl, "GET", null);//调用获取openid接口
				if(!StringUtils.isBlank(resultStr)&&resultStr.indexOf("openid")>0){
					jsonObject =JSONObject.parseObject(resultStr);
					openid=jsonObject.get("openid").toString();
					log.info("userService.getOneByOpenid" + "...." + openid);
					user = userService.getOneByOpenid(openid);
					if(user==null){
						log.info("user==null");
						if(resultStr.indexOf("access_token")>0){
							access_token=jsonObject.get("access_token").toString();
						}
						userinfoUrl= userinfoUrl.replace("ACCESS_TOKEN", access_token).replace("OPEN_ID", openid);
						resultStr = HttpsUtil.httpsRequest(userinfoUrl, "GET", null);//拉取用户信息
						if(!StringUtils.isBlank(resultStr) && resultStr.indexOf("openid")>0){//判断返回值是否含有openid
							jsonObject = JSONObject.parseObject(resultStr);
							//这里可以用oppenid获取数据库t_user表里的user信息判断是否已经存在该user
								user=CommondUtil.getWxUser(jsonObject);
								//开始插入用户信息
								String nickName=StringFormat.toSubString(user.getNickname());
								if("".equals(nickName)){
									user.setNickname("...");
								}else{
									user.setNickname(nickName);
								}
								user.setCreateTime(new Date());
								userService.insertSelective(user);
								log.error("userService.insertSelective" + user);
						}
				}
				SessionUtil.setUser(request, user);
				log.error("SessionUtil.setUser" + user);
//				response.sendRedirect("*****?openid="+openid);//跳转至前端 html
				response.sendRedirect("http://localhost:4003/");
				log.info("开始到了微信回调");
			}else{//授权失败或者网络异常
				log.error("授权失败,返回code为："+code+"获取openid地址:"+requesUrl);
			}
		}else{
			//获取code失败 用户不同意授权，以游客身份进入
			log.error("获取code失败....");
		}
	} catch (Exception e) {
			log.error("发生异常："+e.getMessage());
	}
		log.info("微信回调结束");
	}*/
}
